﻿var console = (function (global) {
    var getDomFromJSON = function (data) {
        var result = [];
        if (Object.prototype.toString.apply(data) === '[object Array]') {
            result = ["<span class = 'log-array'>&nbsp;<a>[Array : ", data.length, "]</a>&nbsp;"];
            result.push("<ol start = 0 style = 'display:none'>");
            for (var i = 0; i < data.length; i++) {
                result.push("<li>");
                result.push(getDomFromJSON(data[i]));
                result.push("</li>")
            }
            result.push("</ol></span>");
        } else if (typeof (data) === "object") {
            result = ["<span class = 'log-object'>&nbsp;<a>[Object]</a>&nbsp;"];
            result.push("<ul style = 'display:none'>");
            for (x in data) {
                result.push("<li>" + x);
                result.push(":" + getDomFromJSON(data[x]));
                result.push("</li>")
            }
            result.push("</ul></span>");
        } else {
            result = ["<span class = 'log-item'>", String(data).replace(/</g, "&lt;").replace(/>/g, "&gt;"), "</span>"];
        }
        return result.join("");
    }

    function objectClicked(e) {
        if (e.target.nodeName !== "A") {
            return;
        }
        function toggle(e) {
            if (e.style.display === "none") {
                e.style.display = "";
            }else {
                e.style.display = "none"
            }
        }

        var elems = {};
        elems["ol"] = e.target.parentNode.getElementsByTagName("ol");
        elems["ul"] = e.target.parentNode.getElementsByTagName("ul");

        for (var i = 0; i < elems["ul"].length; i++) {
            toggle(elems["ul"][i]);
        }
        for (var i = 0; i < elems["ol"].length; i++) {
            toggle(elems["ol"][i]);
        }
    }

    var write = function () {
        var text = document.createElement("div");
        var msg = [];
        for (var i = 0; i < arguments.length; i++) {
            msg.push(getDomFromJSON(arguments[i]));
        }
        text.className = "log";
        text.innerHTML = ["<span class='log-time'>[", new Date().toLocaleTimeString(), "]&nbsp;</span>"].join("") + msg.join(" ");
        text.onclick = objectClicked;
        document.getElementById("output").appendChild(text);
        return text;
    };

    return {
        "log": write,
        "error": function () {
            var line = write.apply(this, arguments);
            line.style.color = "RED";
            return line;
        },
        "clear": function () {
            document.getElementById("output").innerHTML = "";
        },
        "html": function (html) {
            document.getElementById("output").appendChild(html);
        },
    }
})(window);